/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package br.com.foxline.manager.search;

import br.com.foxline.enums.TypeDocument;
import br.com.foxline.model.*;
import br.com.foxline.service.*;
import br.com.foxline.util.ConverterImg;
import br.com.foxline.util.Msg;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.PostConstruct;
import javax.ejb.AccessLocalException;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;

/**
 *
 * @author roniere
 */
@ManagedBean
@ViewScoped
public class ManagerSearchCep implements Serializable {

    @EJB
    StampService stampService;
    @EJB
    TypeStampService typeStampService;
    @EJB
    CharterService charterService;
    @EJB
    PeopleService peopleService;
    @EJB
    PartService partService;
    @EJB
    AnnexService annexService;
    @EJB
    QualityService qualityService;
    @EJB
    NatureWritingService natureWritingService;
    @EJB
    CityService cityService;
    @EJB
    ActCepService actCepService;
    private Charter charter;
    private Charter charterShow;
    private Charter charterEdit;
    private List<Charter> charters;
    private People people;
    private People peopleEdit;
    private Part part;
    private Part partEdit;
    private Stamp stamp;
    private Stamp stampEdit;
    private TypeStamp typeStampObj;
    private String cepEdit;
    private String cepShow;
    private List<Annex> lstAnnex;
    private Annex annexToRemove;
    private Charter charterSelection;
    private NatureWriting natureWriting;
    private City city;
    private String filter;
    private List<ActCep> actCeps;
    private List<NatureWriting> natureWritings;
    
    private ActCep actCep;
    private NatureWriting natureWritingAux;
 
    @PostConstruct
    public void init() {
        charter = new Charter();
        charterShow = new Charter();
        charterEdit = new Charter();
        people = new People();
        people.setTipoDocumento(TypeDocument.CPF);

        peopleEdit = new People();
        peopleEdit.setTipoDocumento(TypeDocument.CPF);

        part = new Part();
        partEdit = new Part();

        stamp = new Stamp();
        stampEdit = new Stamp();

        typeStampObj = new TypeStamp();
        charters = new ArrayList<Charter>();

        filter = "book";
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
        cepEdit = params.get("cepEdit");
        cepShow = params.get("cepShow");
        paramPost();

        actCeps = new ArrayList<ActCep>();
        natureWritings = new ArrayList<NatureWriting>();
        loadActCep();
        loadNature();
    }

    public void remove(Charter c) {
        try {
            charterService.delete(c);
            charters.remove(c);
            Msg.messagemInfo("Excluído com Sucesso");
        } catch (AccessLocalException e) {
            Msg.messagemError("Cliente não autorizado para esta chamada");
            e.printStackTrace();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
    }

    public void paramPost() {
        try {
            if (cepShow != null) {
                charterShow = charterService.find(Long.parseLong(cepShow));
                if (charterShow != null) {
                    charterShow.setAnnex(annexService.getAnnexByCharter(charterShow));
                }
            } else if (cepEdit != null) {
                charterEdit = charterService.find(Long.parseLong(cepEdit));
                if (charterEdit != null) {
                    charterEdit.setAnnex(annexService.getAnnexByCharter(charterEdit));
                    if (charterEdit.getNatureWriting() != null) {
                        natureWriting = charterEdit.getNatureWriting();
                    }
                    lstAnnex = charterEdit.getAnnex();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public String getFilter() {
        return filter;
    }

    public void setFilter(String filter) {
        this.filter = filter;
    }

    public Charter getCharterSelection() {
        return charterSelection;
    }

    public void setCharterSelection(Charter charterSelection) {
        this.charterSelection = charterSelection;
    }

    public List<Annex> getLstAnnex() {
        return lstAnnex;
    }

    public void setLstAnnex(List<Annex> lstAnnex) {
        this.lstAnnex = lstAnnex;
    }

    public Part getPartEdit() {
        return partEdit;
    }

    public void setPartEdit(Part partEdit) {
        this.partEdit = partEdit;
    }

    public Stamp getStampEdit() {
        return stampEdit;
    }

    public void setStampEdit(Stamp stampEdit) {
        this.stampEdit = stampEdit;
    }

    public People getPeopleEdit() {
        return peopleEdit;
    }

    public void setPeopleEdit(People peopleEdit) {
        this.peopleEdit = peopleEdit;
    }

    public List<Charter> getCharters() {
        return charters;
    }

    public Charter getCharterEdit() {
        return charterEdit;
    }

    public void setCharterEdit(Charter charterEdit) {
        this.charterEdit = charterEdit;
    }

    public void setCharters(List<Charter> charters) {
        this.charters = charters;
    }

    public TypeStamp getTypeStampObj() {
        return typeStampObj;
    }

    public Charter getCharterShow() {
        return charterShow;
    }

    public void setCharterShow(Charter charterShow) {
        this.charterShow = charterShow;
    }

    public void setTypeStampObj(TypeStamp typeStampObj) {
        this.typeStampObj = typeStampObj;
    }

    public String getCepEdit() {
        return cepEdit;
    }

    public void setCepEdit(String cepEdit) {
        this.cepEdit = cepEdit;
    }

    public String getCepShow() {
        return cepShow;
    }

    public void setCepShow(String cepShow) {
        this.cepShow = cepShow;
    }

    public City getCity() {
        return city;
    }

    public void setCity(City city) {
        this.city = city;
    }

    public NatureWriting getNatureWriting() {
        return natureWriting;
    }

    public void setNatureWriting(NatureWriting natureWriting) {
        this.natureWriting = natureWriting;
    }

    public Part getPart() {
        return part;
    }

    public void setPart(Part part) {
        this.part = part;
    }

    public Stamp getStamp() {
        return stamp;
    }

    public void setStamp(Stamp stamp) {
        this.stamp = stamp;
    }

    public Charter getCharter() {
        return charter;
    }

    public void setCharter(Charter charter) {
        this.charter = charter;
    }

    public People getPeople() {
        return people;
    }

    public void setPeople(People people) {
        this.people = people;
    }

    public void typeDocumentPeople() {
        System.err.println(people.getTipoDocumento());
    }

    public void search() {
        part.setPeople(people);
        charter.setActCep(actCep);
        charter.setNatureWriting(natureWritingAux);
        
        System.err.println(actCep);
        charters = charterService.searchCharter(charter, part, stamp, filter);
    }

    public void handleSearch() {
        part.setPeople(people);
        charters = charterService.searchCharter(charter, part, stamp, filter);
    }

    public List<Quality> autocompleteQuality(String str) {
        return qualityService.autoComplete(str);
    }

    public void addPartsEdit() {

        if (peopleEdit.getName().isEmpty() || peopleEdit.getName() == null) {
            Msg.messagemError("O nome da parte é obrigatório");
            return;
        }

        if (partEdit.getPartQuality() != null) {
            partEdit.setPartQuality(qualityService.find(partEdit.getPartQuality().getId()));
        }

        if (peopleEdit != null && peopleEdit.getId() != null) {
            peopleService.update(peopleEdit);
        }

        partEdit.setPeople(peopleEdit);
        charterEdit.getParts().add(partEdit);

        peopleEdit = new People();
        peopleEdit.setTipoDocumento(TypeDocument.CPF);
        partEdit = new Part();

    }

    public void addStampsEdit() {
        stampEdit.setTypeStamp(typeStampService.find(typeStampObj.getId()));

        if (charterEdit.getStamp() != null && !charterEdit.getStamp().isEmpty()) {
            charterEdit.getStamp().add(stampEdit);
        } else {
            List<Stamp> lsrt = new ArrayList<Stamp>();
            lsrt.add(stampEdit);
            charterEdit.setStamp(lsrt);
        }
        stampEdit = new Stamp();
    }

    public void ajaxVerifyPeopleExist() {
        String doc = "";
        if (peopleEdit.getTipoDocumento() == TypeDocument.CNPJ) {
            doc = peopleEdit.getCnpj();
        } else if (peopleEdit.getTipoDocumento() == TypeDocument.CPF) {
            doc = peopleEdit.getCpf();
        } else if (peopleEdit.getTipoDocumento() == TypeDocument.OAB) {
            doc = peopleEdit.getOAB();
        }
        if (doc == null || doc.isEmpty()) {
            return;
        }
        People pe = peopleService.existPeople(peopleEdit.getTipoDocumento(), doc);
        if (pe != null) {
            peopleEdit = pe;
        }
        if (peopleEdit.getTipoDocumento() == null) {
            if (peopleEdit.getCpf() != null && peopleEdit.getCpf().length() == 11) {
                peopleEdit.setTipoDocumento(TypeDocument.CPF);
            } else if (peopleEdit.getCnpj() != null && peopleEdit.getCnpj().length() == 14) {
                peopleEdit.setTipoDocumento(TypeDocument.CNPJ);
            } else {
                peopleEdit.setTipoDocumento(TypeDocument.CPF);
            }
        }
    }

    public void removePart(int p) {
        charterEdit.getParts().remove(p);
    }

    public void editPart(int p) {
        peopleEdit = charterEdit.getParts().get(p).getPeople();

        if (peopleEdit.getTipoDocumento() == null) {
            if (peopleEdit.getCpf() != null && peopleEdit.getCpf().length() == 11) {
                peopleEdit.setTipoDocumento(TypeDocument.CPF);
            } else if (peopleEdit.getCnpj() != null && peopleEdit.getCnpj().length() == 14) {
                peopleEdit.setTipoDocumento(TypeDocument.CNPJ);
            } else {
                peopleEdit.setTipoDocumento(TypeDocument.CPF);
            }
        }

        charterEdit.getParts().remove(p);
    }

    public void removeStamp(int p) {
        charterEdit.getStamp().remove(p);
    }

    public void removeAnnexAux(Annex p) {
        annexToRemove = p;
    }

    public void removeAnnex() {
        if (annexToRemove != null) {
            charterEdit.getAnnex().remove(annexToRemove);
        }
    }

    public void edit() {
        charterEdit.setCity(city);
        if (natureWriting != null && natureWriting.getId() != null) {
            charterEdit.setNatureWriting(natureWritingService.find(natureWriting.getId()));
        }
        if (city != null && city.getId() != null) {
            charterEdit.setCity(city);
        }
        charterEdit.setAnnex(lstAnnex);
        charterService.update(charterEdit);
        Msg.messagemInfo("Atualizado com Sucesso !");
        charterEdit = charterService.find(charterEdit.getId());
        natureWriting = charterEdit.getNatureWriting();
        charterEdit.setAnnex(annexService.getAnnexByCharter(charterEdit));
        lstAnnex = charterEdit.getAnnex();
    }

    public void handle(FileUploadEvent event) throws IOException {
        handleAux(event.getFile().getContents(), event.getFile().getFileName(),
                event.getFile().getContentType(), event.getFile().getInputstream());
    }

    private void handleAux(byte[] imageBytes, String nome, String tipo, InputStream is) throws IOException {

        byte[] bytes = null;

        Annex annex = new Annex();
        if (tipo.equalsIgnoreCase("image/tiff")) {
            bytes = ConverterImg.convertTiffToJpg(is);
            annex.setType("jpeg");
            annex.setDescription(nome.replaceAll("tif|tiff", "jpeg"));
        } else {
            bytes = imageBytes;
            annex.setType(tipo);
            annex.setDescription(nome);
        }
        if (bytes != null) {
            annex.setFileByte(bytes);
            lstAnnex.add(annex);
            System.err.println("Annexoo..." + lstAnnex.size());
            annex = new Annex();
            Msg.messagemWarn("Anexado");
        }

    }

    public void redirect(String url) {

        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().redirect(url);
        } catch (IOException ex) {
            Logger.getLogger(ManagerSearchCep.class.getName()).log(Level.SEVERE, null, ex);
        }


    }

    public void loadActCep() {
        actCeps = actCepService.findAll();
    }

    public void loadNature() {
        natureWritings = natureWritingService.findAll();
    }
    
     public void initActCep(){
        actCep = new ActCep();
        charter.setActCep(new ActCep());
        search();
    }
    public void initNature(){
        natureWritingAux = new NatureWriting();
        charter.setNatureWriting(new NatureWriting());
    }

    public List<ActCep> getActCeps() {
        return actCeps;
    }

    public void setActCeps(List<ActCep> actCeps) {
        this.actCeps = actCeps;
    }

    public List<NatureWriting> getNatureWritings() {
        return natureWritings;
    }

    public void setNatureWritings(List<NatureWriting> natureWritings) {
        this.natureWritings = natureWritings;
    }

    public ActCep getActCep() {
        return actCep;
    }

    public void setActCep(ActCep actCep) {
        this.actCep = actCep;
    }

    public NatureWriting getNatureWritingAux() {
        return natureWritingAux;
    }

    public void setNatureWritingAux(NatureWriting natureWritingAux) {
        this.natureWritingAux = natureWritingAux;
    }
        
    

    
}
